import 'dart:io';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart';
import 'package:archive/archive.dart';
import 'package:archive/archive_io.dart';
import 'package:get/get.dart';

class OfflineDownloadPage extends StatefulWidget {
  const OfflineDownloadPage({super.key});

  @override
  State<StatefulWidget> createState() => _OfflineDownloadPage();
}

class _OfflineDownloadPage extends State<StatefulWidget> {
  String title = 'OfflineWebView';

  String statusStr = '未解压';
  bool status = false;
  late String filePath;

  @override
  void initState() {
    super.initState();
    exists('html/www/offline').then((value) {
      if (value) {
        createPath('html/www/offline').then((value) {
          setState(() {
            statusStr = '已解压，可访问';
            status = true;
            filePath = value;
          });
        });
      }
    });
  }

  Future<bool> exists(path) async {
    final directory = await getApplicationDocumentsDirectory();
    String dirpath = directory.path;
    String newPath = '$dirpath/$path';
    Directory newDirectory = Directory(newPath);
    return await newDirectory.exists();
  }

  Future<String> createPath(String path) async {
    final directory = await getApplicationDocumentsDirectory();
    String dirpath = directory.path;
    print('temp dir: $dirpath');
    final pathList = path.split('/');
    String curPath = '';
    for (var element in pathList) {
      curPath = '$curPath/$element';
      String newPath = '$dirpath$curPath';
      Directory newDirectory = Directory(newPath);
      if (!await newDirectory.exists()) {
        try {
          await newDirectory.create();
        } catch (e) {
          print('create dir $e');
        }
      }
    }
    return '$dirpath$curPath';
  }

  Future<void> downloadFile() async {
    //模拟下载文件
    String downloadPath = await createPath('download');
    Directory newDirectory = Directory(downloadPath);

    // 如果目录不存在，则尝试创建它
    if (!await newDirectory.exists()) {
      try {
        await newDirectory.create();
      } catch (e) {
        print('create dir $e');
      }
    }
    final ByteData data = await rootBundle.load('assets/offline.zip');
    final List<int> bytes = data.buffer.asUint8List();
    String toFilePath = '$downloadPath/offline.zip';

    final toFile = File(toFilePath);
    //不重复下载 通常一个版本一个文件名
    // if (!await toFile.exists()) {
    // 复制文件
    await toFile.writeAsBytes(bytes);
    // }
    await unzipHtml();
  }

  Future<void> unzipHtml() async {
    String htmlPath = await createPath('html/www/offline');
    String downloadPath = await createPath('download');
    String zipPath = '$downloadPath/offline.zip';
    final zipFile = File(zipPath);
    // 创建Archive对象
    Archive archive = ZipDecoder().decodeBytes(await zipFile.readAsBytesSync());

    // 将Zip存档的内容解压缩到磁盘。
    for (ArchiveFile file in archive) {
      if (file.isFile) {
        List<int> data = file.content;
        File(htmlPath + "/" + file.name)
          ..createSync(recursive: true)
          ..writeAsBytesSync(data);
      } else {
        Directory(htmlPath + "/" + file.name)..create(recursive: true);
      }
    }
    print('解压完成');
    setState(() {
      statusStr = '解压完成，可打开';
      status = true;
      filePath = htmlPath;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(title),
      ),
      body: Center(
        child: Column(children: [
          Text(statusStr),
          FilledButton(
            onPressed: () {
              // 处理按钮点击事件
              downloadFile();
            },
            child: Text('模拟下载'),
          ),
          FilledButton(
            onPressed: () {
              // 处理按钮点击事件
              if (status) {
                Get.toNamed('/web-off/page', arguments: {'filePath': filePath});
                // Navigator.of(context).pushNamed('/web-off/page',
                //     arguments: {'filePath': filePath});
              }
            },
            child: Text('打开离线页面'),
          )
        ]),
      ),
    );
  }
}
